package com.android.ailaoshan.index.fragment;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.ailaoshan.R;
import com.android.ailaoshan.collection.fragment.PictureFragment;
import com.android.ailaoshan.collection.fragment.SoundFragment;
import com.google.android.material.tabs.TabLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class CollectionFragment extends Fragment {

    private Context mContext;

    private View collectionView;

    /**
     * 碎片标识
     * 0 图片碎片
     * 1 声音碎片
     */
    private int fragmentId = 0;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mContext = getContext();
        collectionView = inflater.inflate(R.layout.collection_fragment,container,false);

        return collectionView;
    }

    @Override
    public void onStart(){
        super.onStart();
        TabLayout tabLayout = collectionView.findViewById(R.id.collection_top_container);

        TabLayout.Tab tabText = tabLayout.newTab();
        tabText.setText("图片");
        tabLayout.addTab(tabText);

        TabLayout.Tab tabPicture = tabLayout.newTab();
        tabPicture.setText("声音");
        tabLayout.addTab(tabPicture);

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                if(position == 0){
                    if(fragmentId != 0){
                        fragmentId = 0;
                        changeFragment(new PictureFragment());
                    }
                }else{
                    if(fragmentId != 1){
                        fragmentId = 1;
                        changeFragment(new SoundFragment());
                    }
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {}

            @Override
            public void onTabReselected(TabLayout.Tab tab) {}
        });

        changeFragment(new PictureFragment());
    }

    /**
     * 碎片替换
     */
    private void changeFragment(Fragment fragment){
        FragmentManager fragmentManager = getChildFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.collection_content_container,fragment);
        transaction.commit();
    }
}
